<template>
	<view class="wrap">
		<view class="wrap__header">
			<view :class="['header__title', titleIndex===index?'header__title--active':'']" 
			v-for="(title, index) in titles" :key="index" @click="titleClick(index)">{{title}}</view>
			<view class="header__search">
				<image src="@/static/icons/search.png"  class="search__icon" @click="searchClick"></image>
			</view>
		</view>
		<view class="wrap__nav">
			<view :class="['nav__item', cateIndex===index?'nav__item--active':'']" 
			@click="cateClick(index)" 
			v-for="(item, index) in cateList" :key="index">
				<text class="item__title">{{item.name}}</text>
				<text class="item__line"></text>
			</view>
		</view>
		<view class="wrap__main">
			<!-- 市场股票 -->
			<market v-if="titleIndex===0" :marketList="marketList" @orderChange="orderTypeChange" :cate="cateList[cateIndex]" 
			:marketIndexList="marketIndexList" :hotList="hotList" ></market>
			<!-- 自选股票 -->
			<optional v-else :optionalList="optionalList" @optionOrderChange="optionOrderChange"
			 @updateOptional="getOptionalList"></optional>
		</view>
	</view>
</template>

<script>
	import {wsUrl} from '@/common/js/config.js'
	import optional from '@/components/find/optional.vue'
	import market from '@/components/find/market.vue'
	export default {
		components:{
			optional,
			market
		},
		data() {
			return {
				titles:[this.$t('market.title'),this.$t('market.optional')], //
				titleIndex:0,  //标题索引
				cateList:[], //国家分类
				cateIndex:0, //导航索引
				optionalList:[], //自选数据列表
				marketList:[], // 市场股票列表
				marketIndexList:[], //市场指数列表
				hotList:[], //热门榜单列表
				indexTimerId:null, //获取指数定时器
				priceOlder:"desc", //价格排序方式 desc //降序 asc升序
				increaseOlder:"", //涨幅排序
				file:"", //当前排序的字段 zhangdieshu 价格  zhangdiebaifenbi涨跌
				order:"",  // desc  降序  asc 升序
			}
		},
		async onShow() {
			// 判断是否登陆
			let token = uni.getStorageSync("token")
			if(!token){
				uni.navigateTo({
					url:"/pages/login/login"
				})
			}else{
				// 獲取地区分類
				await this.getAreaCate()
				// 获取自选 市场数据
				this.getDatas()
			}
		},
		onHide() {
			this.indexTimerId && clearInterval(this.indexTimerId)
		},
		methods:{
			
			// 市场排序类型点击
			orderTypeChange(type){
				// this.file = type
				    console.log(this.file)
				    this.order = this.order === "desc" ? "asc" :"desc"
				    // this.getMarketList()
				    console.log(this.order)
				    if(this.order == 'asc'){
				     this.marketList.sort((a, b) => b.price - a.price);
				    }else
				    {
				     this.marketList.sort((a, b) => a.price - b.price);
				    }
				    // this.marketList.sort((a, b) => a.price - b.price);
				    
					
				// this.file = type
				// this.order = this.order === "desc" ? "asc" :"desc"
				// this.getMarketList()
			},
			// 自选排序类型切换
			optionOrderChange(type){
				this.file = type
				this.order = this.order === "desc" ? "asc" :"desc"
				this.getOptionalList()
			},
			// 获取自选 市场数据
			getDatas(){
				// 获取自选数据
				this.getOptionalList()
				// 获取市场指数
				this.getMarketIndex()
				this.indexTimerId && clearInterval(this.indexTimerId)
				// this.indexTimerId = setInterval(()=>{
				// 	this.getMarketIndex()
				// }, 3000)
				// 获取市场列表
				this.getMarketList()
				// 获取市场热门列表
				this.getHotMarketList()
			},
			// 获取市场热门列表
			async getHotMarketList(){
				let {id} = this.cateList[this.cateIndex]
				let res = await this.$api.getHotStock(id)
				if(res.code === 1 && res.data){
					this.hotList = res.data
				}
			},
			// 获取市场指数列表
			async getMarketIndex(){
				let {id} = this.cateList[this.cateIndex]
				let res = await this.$api.getMarketIndex(id)
				if(res.code === 1 && res.data){
					this.marketIndexList = res.data
				}
			},
			//地区分类切换
			cateClick(index){
				if(this.cateIndex !== index){
					this.cateIndex = index
					this.getDatas()
				}
			},
			// 獲取行情頁分類
			async getAreaCate(){
				let res = await this.$api.getAreaCate()
				if(res.code === 1 && res.data){
					this.cateList = res.data
				}
			},
			// 标题点击
			titleClick(index){
				if(this.titleIndex !== index){
					this.titleIndex = index
				}
			},
			//获取自选股票列表
			async getOptionalList(){
				let {id} = this.cateList[this.cateIndex]
				let res = await this.$api.getOptionalList(id)
				if(res.code === 1 && res.data){
					if(res.data.length){
						this.optionalList = res.data.map(item=>{
							//item.product.codeName = item.product.zimudaima
							return item
						})
					}else{
						this.optionalList = []
					}
				}
			},
			// 获取市场股票列表
			async getMarketList(){
				let {id} = this.cateList[this.cateIndex]
				let {url} = '';
				if(id == 1){
					 url = 'https://api.investing.com/api/financialdata/assets/equitiesByCountry/default?fields-list=id%2Cname%2Csymbol%2CisCFD%2Chigh%2Clow%2Clast%2ClastPairDecimal%2Cchange%2CchangePercent%2Cvolume%2Ctime%2CisOpen%2Curl%2Cflag%2CcountryNameTranslated%2CexchangeId%2CperformanceDay%2CperformanceWeek%2CperformanceMonth%2CperformanceYtd%2CperformanceYear%2Cperformance3Year%2CtechnicalHour%2CtechnicalDay%2CtechnicalWeek%2CtechnicalMonth%2CavgVolume%2CfundamentalMarketCap%2CfundamentalRevenue%2CfundamentalRatio%2CfundamentalBeta%2CpairType&country-id=35&page=0&page-size=100&include-major-indices=false&include-additional-indices=false&include-primary-sectors=false&include-other-indices=false&limit=0';
				}
				if(id == 2){
					 url = 'https://api.investing.com/api/financialdata/assets/equitiesByCountry/default?fields-list=id%2Cname%2Csymbol%2CisCFD%2Chigh%2Clow%2Clast%2ClastPairDecimal%2Cchange%2CchangePercent%2Cvolume%2Ctime%2CisOpen%2Curl%2Cflag%2CcountryNameTranslated%2CexchangeId%2CperformanceDay%2CperformanceWeek%2CperformanceMonth%2CperformanceYtd%2CperformanceYear%2Cperformance3Year%2CtechnicalHour%2CtechnicalDay%2CtechnicalWeek%2CtechnicalMonth%2CavgVolume%2CfundamentalMarketCap%2CfundamentalRevenue%2CfundamentalRatio%2CfundamentalBeta%2CpairType&country-id=5&page=0&page-size=100&include-major-indices=false&include-additional-indices=false&include-primary-sectors=false&include-other-indices=false&limit=0';
					
				}
				if(id == 3){
					 url = 'https://api.investing.com/api/financialdata/assets/equitiesByCountry/default?fields-list=id%2Cname%2Csymbol%2CisCFD%2Chigh%2Clow%2Clast%2ClastPairDecimal%2Cchange%2CchangePercent%2Cvolume%2Ctime%2CisOpen%2Curl%2Cflag%2CcountryNameTranslated%2CexchangeId%2CperformanceDay%2CperformanceWeek%2CperformanceMonth%2CperformanceYtd%2CperformanceYear%2Cperformance3Year%2CtechnicalHour%2CtechnicalDay%2CtechnicalWeek%2CtechnicalMonth%2CavgVolume%2CfundamentalMarketCap%2CfundamentalRevenue%2CfundamentalRatio%2CfundamentalBeta%2CpairType&country-id=4&page=0&page-size=100&include-major-indices=false&include-additional-indices=false&include-primary-sectors=false&include-other-indices=false&limit=0';
				}
				
				uni.request({
				    url: url,
					method: 'GET',
				    data: {},
				    success: (res) => {
				       
						let total = res.data.total
						let list = res.data?.data || []
						
						
						this.marketList  = list.map(item=>{
							item.id = item.Id
							item.codeName = item.Symbol
							item.category_id = 1
							item.close = item.Low
							item.code = item.Symbol
							item.discount = item.Low
							item.high = item.High
							item.low = item.Low
							item.name = item.Name
							item.open = item.Last
							item.price = item.Last
							item.shichang = item.Flag
							item.shuzidaima = item.Symbol
							item.turnover = item.Symbol
							item.turnover_section = item.Symbol
							item.vol = item.Volume
							item.zhangdiebaifenbi = item.ChgPct
							item.zhangdieshu = item.Chg
							item.zimudaima = item.Symbol
							item.zongshizhi = item.FundamentalMarketCap
							return item
						})
						
				    },
				    fail: (err) => {
				        console.error(err); // 请求失败的错误信息
				    }
				});
				
				// let res = await this.$api.getMarketList(id, 1, this.file, this.order)
				// if(res.code === 1 && res.data?.data){
				// 	let total = res.data.total
				// 	let list = res.data?.data || []
				// 	// 原始数据
				// 	if(list.length){
				// 		this.marketList  = list.map(item=>{
				// 			item.codeName = item.zimudaima.split(":")[0]
				// 			return item
				// 		})
				// 	}else{
				// 		this.marketList = []
				// 	}
				// }
			},
			// 搜索點擊
			searchClick(){
				uni.navigateTo({
					url:"/pages/find/search"
				})
			}
		}
	}
</script>

<style lang="scss">
	.wrap {
		padding:  0 30rpx;
		padding-top: 40rpx;
		box-sizing: border-box;
		.wrap__header{
			@include flexRowAlign();
			align-items: flex-end;
			.header__title{
				font-size: 36rpx;
				color: #fff;
				margin-right: 50rpx;
			}
			.header__title--active{
				font-size: 46rpx;
				color: #fff;
			}
			.header__search{
				flex: 1;
				@include flexRowAlign(flex-end);
				.search__icon{
					width: 38rpx;
					height: 38rpx;
				}
			}
		}
		.wrap__nav{
			margin-top: 40rpx;
			@include flexRowAlign();
			.nav__item{
				margin-right: 90rpx;
				@include flexCenter(column);
				.item__title{
					font-size: 32rpx;
					font-weight: bold;
					color: #fff;
				}
				.item__line{
					width: 30rpx;
					height: 4rpx;
					background: transparent;
					border-radius: 2rpx;
					margin-top: 4rpx;
				}
			}
			.nav__item--active{
				.item__title{
					color: #458EF4;
				}
				.item__line{
					background: #458EF4;
				}
			}
		}
	}
</style>